﻿using System;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using B.MESUI.Login.A_Public.Service;
using B.MESUI.Login.Properties;

public partial class CodeRuleSelector : XtraUserControl
{
    private ComboBoxEdit _ruleComboBox;
    private TextEdit _previewCodeTextBox;
    private LabelControl _labelRule;
    private bool _isAdmin = false;
    private string _defaultRule = "AddWorkOrder"; // 默认规则，可由外部页面设置

    /// <summary>
    /// 默认编码规则（可由外部页面设置）
    /// </summary>
    public string DefaultRule
    {
        get => _defaultRule;
        set => _defaultRule = value;
    }

    /// <summary>
    /// 是否管理员。管理员可选规则，普通用户只显示预览。
    /// </summary>
    public bool IsAdmin
    {
        get => _isAdmin;
        set
        {
            _isAdmin = value;
            UpdateRuleComboBoxVisibility();
        }
    }

    /// <summary>
    /// 当前选中的编码规则
    /// </summary>
    public string SelectedRule => _ruleComboBox.Text.Trim();

    /// <summary>
    /// 当前预览编码
    /// </summary>
    public string PreviewCode => _previewCodeTextBox.Text;

    public CodeRuleSelector()
    {
        InitLayout();
        this.Load += CodeRuleSelector_Load;
    }

    private async void CodeRuleSelector_Load(object sender, EventArgs e)
    {
        await LoadCodeRules();

        if (_isAdmin)
        {
            // 管理员可见下拉框
            _labelRule.Visible = _ruleComboBox.Visible = true;
            string savedRule = Settings.Default.CodeRule;
            if (!string.IsNullOrEmpty(savedRule) && _ruleComboBox.Properties.Items.Contains(savedRule))
            {
                _ruleComboBox.SelectedItem = savedRule;
            }
            else if (_ruleComboBox.Properties.Items.Contains(_defaultRule))
            {
                _ruleComboBox.SelectedItem = _defaultRule;
            }
            else if (_ruleComboBox.Properties.Items.Count > 0)
            {
                _ruleComboBox.SelectedIndex = 0;
            }
            string previewCode = await CodeGenService.PreviewCodeAsync(_ruleComboBox.Text);
            _previewCodeTextBox.Text = previewCode;
        }
        else
        {
            // 普通用户只显示预览
            _labelRule.Visible = _ruleComboBox.Visible = false;
            string savedRule = Settings.Default.CodeRule;
            string ruleToUse = !string.IsNullOrEmpty(savedRule) ? savedRule : _defaultRule;
            string previewCode = await CodeGenService.PreviewCodeAsync(ruleToUse);
            _previewCodeTextBox.Text = previewCode;
        }
        AdjustSize();
    }

    /// <summary>
    /// 初始化控件布局
    /// </summary>
    private  void InitLayout()
    {
        this.SuspendLayout();

        _labelRule = new LabelControl
        {
            Text = "编码规则：",
            Location = new Point(0, 5),
            Size = new Size(70, 22)
        };
        _ruleComboBox = new ComboBoxEdit
        {
            Location = new Point(75, 0),
            Size = new Size(150, 28),
            Properties = { NullText = "选择编码规则" }
        };
        _ruleComboBox.SelectedIndexChanged += RuleComboBox_SelectedIndexChanged;

        _previewCodeTextBox = new TextEdit
        {
            Location = new Point(0, 40),
            Size = new Size(240, 28),
            Properties = { ReadOnly = true, NullText = "编码预览" }
        };

        this.Controls.Add(_labelRule);
        this.Controls.Add(_ruleComboBox);
        this.Controls.Add(_previewCodeTextBox);

        this.ResumeLayout(false);
        this.PerformLayout();
    }

    /// <summary>
    /// 加载所有编码规则
    /// </summary>
    private async Task LoadCodeRules()
    {
        var rules = await CodeGenService.GetAllRulesAsync();
        _ruleComboBox.Properties.Items.Clear();
        _ruleComboBox.Properties.Items.AddRange(rules.Select(r => r.ruleName).ToArray());
    }

    /// <summary>
    /// 管理员选择规则后，保存并刷新预览
    /// </summary>
    private async void RuleComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (_isAdmin && _ruleComboBox.SelectedIndex >= 0)
        {
            // 保存管理员选择的规则
            Settings.Default.CodeRule = _ruleComboBox.Text;
            Settings.Default.Save();
            // 刷新预览
            string previewCode = await CodeGenService.PreviewCodeAsync(_ruleComboBox.Text);
            _previewCodeTextBox.Text = previewCode;
            AdjustSize();
        }
    }

    /// <summary>
    /// 保存时调用，返回正式编码（普通用户用管理员已选规则，管理员用当前选中规则）
    /// </summary>
    public async Task<string> GetFinalCodeAsync()
    {
        string ruleToUse;
        if (_isAdmin)
        {
            ruleToUse = _ruleComboBox.Text;
            // 保存管理员选择
            Settings.Default.CodeRule = ruleToUse;
            Settings.Default.Save();
        }
        else
        {
            ruleToUse = Settings.Default.CodeRule;
            if (string.IsNullOrEmpty(ruleToUse))
                ruleToUse = _defaultRule;
        }
        if (string.IsNullOrEmpty(ruleToUse))
            throw new Exception("编码规则未设置！");
        string code = await CodeGenService.GenerateCodeAsync(ruleToUse);
        if (string.IsNullOrEmpty(code))
            throw new Exception("生成编码失败！");
        _previewCodeTextBox.Text = code;
        AdjustSize();
        return code;
    }

    /// <summary>
    /// 控制下拉框显示/隐藏
    /// </summary>
    private void UpdateRuleComboBoxVisibility()
    {
        _labelRule.Visible = _ruleComboBox.Visible = _isAdmin;
    }

    /// <summary>
    /// 根据内容自适应控件大小
    /// </summary>
    private void AdjustSize()
    {
        int ruleWidth = TextRenderer.MeasureText(_ruleComboBox.Text, _ruleComboBox.Font).Width + 100;
        int previewWidth = TextRenderer.MeasureText(_previewCodeTextBox.Text, _previewCodeTextBox.Font).Width + 100;
        int width = Math.Max(ruleWidth, previewWidth) + 75;
        width = Math.Max(width, 350);

        _ruleComboBox.Width = width - 75;
        _previewCodeTextBox.Width = width - 75;

        this.Width = width;
        this.Height = 70;
    }

    private void InitializeComponent()
    {
            this.SuspendLayout();
            // 
            // CodeRuleSelector
            // 
            this.Name = "CodeRuleSelector";
            this.Load += new System.EventHandler(this.CodeRuleSelector_Load_1);
            this.ResumeLayout(false);

    }

    private void CodeRuleSelector_Load_1(object sender, EventArgs e)
    {

    }
}